package com.itheima.reggie.common;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.InputStream;

@Component
public class OssClient {
    @Value("${aliyunOss.endpoint}")
    private String endpoint;
    @Value("${aliyunOss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyunOss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyunOss.bucketName}")
    private String bucketName;


    //接收一个文件的流，完成oss的上传，并且返回文件的完整访问路径
    public String transferToAliyunOss(String fileName, InputStream file){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            ossClient.putObject(bucketName,fileName , file);
        } catch (OSSException oe) {

        } catch (ClientException ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "https://chengdu-reggie-62-huige.oss-cn-chengdu.aliyuncs.com/"+fileName;
    }
}
